package com.hy.mydesktop.client.mvc.desktop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.desktop.client.Desktop;
import com.extjs.gxt.desktop.client.TaskBar;
import com.extjs.gxt.samples.resources.client.TestData;
import com.extjs.gxt.samples.resources.client.model.Stock;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.hy.mydesktop.client.component.event.AppEvents;
import com.hy.mydesktop.client.component.factory.GxtDesktopComponentFactory;
import com.hy.mydesktop.client.component.mvc.event.EventStructureMetaModel;
import com.hy.mydesktop.client.component.type.ComponentTypeEnum;
import com.hy.mydesktop.client.mvc.base.BaseController;
import com.hy.mydesktop.shared.persistence.domain.gxt.GxtComponentMetaNodeModel;

public class DesktopStartMenuView extends View {

	private Desktop desktop = null;
	private MenuItem menuItem = null;
	
	public DesktopStartMenuView(Controller controller) {
		super(controller);
	}

	@Override
	protected void handleEvent(AppEvent event) {
		if (desktop==null) {
			//desktop = (Desktop)map.get("desktop");
			desktop = Registry.get("desktop");
		}
		//读取事件中的所有数据信息
		 Map<String, Object> map = event.getData();
		//0002
		/**
		  * 触发AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER事件
		  * 根据((BaseController)this.getController()).getViewData()  获取视图的标识
		  * 创建并初始化视图
		  */
		if (AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER==event.getType()) {
			 /**
			 * data 可以是需要加载的菜单的元模型信息
			 *     也可以是用户信息，调用后台业务逻辑，获得需要加载的菜单的元模型信息
			 */
			 
		    //添加一个快捷方式
			desktop = (Desktop)map.get("desktop");
			EventStructureMetaModel eventstructuremetamodel = (EventStructureMetaModel)map.get("eventstructuremetamodel");
			String viewDataCode=((BaseController)this.getController()).getViewData();
			GxtComponentMetaNodeModel gxtComponentMetaNodeModel = null;
			
			if (viewDataCode!=null) {
				/**
				 * 调用后台业务逻辑，获得viewDataCode，对应的元模型
				 */
				if (viewDataCode.equals("desktopStartMenu_viewData_init_01")) {
					gxtComponentMetaNodeModel = this.getGxtComponentMetaNodeModel();
				}
				
				if (viewDataCode.equals("desktopStartMenu_viewData_init_02")) {
					gxtComponentMetaNodeModel = this.getGxtComponentMetaNodeModel2();
				}
				
			}
			/**
			 * 如何获取自己需要的信息，创建一个自定义的Shortcut
			 */
			
			
//			menuItem = (MenuItem)GxtDesktopComponentFactory.addOneGxtComponentToDesktop(desktop, gxtComponentMetaNodeModel);
			menuItem = (MenuItem)GxtDesktopComponentFactory.addOneGxtComponentToDesktop( gxtComponentMetaNodeModel);
		};
		
		//0003
		if (AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT==event.getType()) {			
		};
		//0005
		if (AppEvents.DESKTOP_STARTMENU_ONCLICK_INIT==event.getType()) {
			
			/**
			 * data 可以是需要加载的菜单的元模型信息
			 *     也可以是用户信息，调用后台业务逻辑，获得需要加载的菜单的元模型信息
			 */
			
			 EventStructureMetaModel eventstructuremetamodel = 
				 (EventStructureMetaModel)map.get("eventstructuremetamodel");
			if (desktop==null) {
				desktop = (Desktop)map.get("desktop");
			}
			TaskBar taskBar = desktop.getTaskBar();
			
			 if (menuItem!=null) {
					String responseModeId = eventstructuremetamodel.getResponseModeId();
					/**
					 * responseModeId标识，调用后台业务逻辑
					 * 触发，初始化某一窗口的事件
					 * 返回一个创建好的窗口
					 * 
					 */
							
					
					if (responseModeId.equals("00_02_66")) {
						/**
						 * 触发，初始化某一窗口的事件
						 * 返回一个创建好的窗口
						 */
						//menuItem 和与之对应的 Window是一一对应的	
						if (menuItem.getData("window")==null) {
							Window window = createGridWindow();
							menuItem.setData("window", window);
							
						}
						Window ww = menuItem.getData("window");
						if (!desktop.getWindows().contains(ww)) {
						      desktop.addWindow(ww);
						    }
						    if (ww != null && !ww.isVisible()) {
						    	ww.show();
						    } else {
						    	ww.toFront();
						    }
					} 
					if (responseModeId.equals("00_02_88")){
						//menuItem 和与之对应的 Window是一一对应的	
						if (menuItem.getData("window")==null) {
							Window window = createGridWindow2();
							menuItem.setData("window", window);
							
						}
						Window ww = menuItem.getData("window");
						if (!desktop.getWindows().contains(ww)) {
						      desktop.addWindow(ww);
						    }
						    if (ww != null && !ww.isVisible()) {
						    	ww.show();
						    } else {
						    	ww.toFront();
						    }
					}
					/**
					 * 以responseModeId作为参数，调用后台业务逻辑
					 */
					
				}
			  
		};
		//0004
		//根据事件类型和事件中包含的数据，响应事件
		if(AppEvents.DESKTOP_SHORTCUT_ONCLICK==event.getType()){//根据事件类型，处理事件
			//根据事件中包含的数据，响应事件，即创建并初始化窗口
			
		//	this.createDynamicDesktop2(event);//最终创建出了桌面快捷方式（View视图）
			/**
			 * 何时添加控件的事件
			 * 1：创建控件的过程中，添加
			 * 识别GxtComponentMetaNodeModel中，Map中某个指，来设置它是否有AppEvent事件，
			 * 如何有AppEvent事件，需要被监听。
			 * 需要在Shortcut工厂中，通过ShortcutModelEnum.AppEven来判断，是否有事件需要监听
			 * 如果判断有，
			 * 根据Shortcut特定的方式，添加事件监听。如 Shortcut.addListener()
			 * 
			 * 2：控件创建完成后，添加
			 * 控件创建完成后，返回的是一个Desktop。
			 * 如何知道，改为哪个控件添加事件
			 */
			/**
			 * 为每个快捷方式，注册单击事件（包括业务事件）
			 */
			//List<Shortcut> list = desktop.getShortcuts();
			//list.get(0).
		}
	}
	
	 private Window createGridWindow() {
		    Window w = new Window();
		    w.setIcon(IconHelper.createStyle("icon-grid"));
		    w.setMinimizable(true);
		    w.setMaximizable(true);
		    w.setHeading("Grid Window");
		    w.setSize(500, 400);
		    w.setLayout(new FitLayout());

		    GroupingStore<Stock> store = new GroupingStore<Stock>();
		    store.add(TestData.getCompanies());
		    store.groupBy("industry");

		    ColumnConfig company = new ColumnConfig("name", "Company", 60);
		    ColumnConfig price = new ColumnConfig("open", "Price", 20);
		    price.setNumberFormat(NumberFormat.getCurrencyFormat());
		    ColumnConfig change = new ColumnConfig("change", "Change", 20);
		    ColumnConfig industry = new ColumnConfig("industry", "Industry", 20);
		    ColumnConfig last = new ColumnConfig("date", "Last Updated", 20);
		    last.setDateTimeFormat(DateTimeFormat.getFormat("MM/dd/y"));

		    List<ColumnConfig> config = new ArrayList<ColumnConfig>();
		    config.add(company);
		    config.add(price);
		    config.add(change);
		    config.add(industry);
		    config.add(last);

		    final ColumnModel cm = new ColumnModel(config);

		    GroupingView view = new GroupingView();
		    view.setForceFit(true);
		    view.setGroupRenderer(new GridGroupRenderer() {
		      public String render(GroupColumnData data) {
		        String f = cm.getColumnById(data.field).getHeader();
		        String l = data.models.size() == 1 ? "Item" : "Items";
		        return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";
		      }
		    });

		    Grid<Stock> grid = new Grid<Stock>(store, cm);
		    grid.setView(view);
		    grid.setBorders(true);

		    w.add(grid);
		    return w;
		  }
	 
	 private Window createGridWindow2() {
		    Window w = new Window();
		    w.setIcon(IconHelper.createStyle("icon-grid"));
		    w.setMinimizable(true);
		    w.setMaximizable(true);
		    w.setHeading("222222Grid Window");
		    w.setSize(500, 400);
		    w.setLayout(new FitLayout());

		    GroupingStore<Stock> store = new GroupingStore<Stock>();
		    store.add(TestData.getCompanies());
		    store.groupBy("industry");

		    ColumnConfig company = new ColumnConfig("name", "Company", 60);
		    ColumnConfig price = new ColumnConfig("open", "Price", 20);
		    price.setNumberFormat(NumberFormat.getCurrencyFormat());
		    ColumnConfig change = new ColumnConfig("change", "Change", 20);
		    ColumnConfig industry = new ColumnConfig("industry", "Industry", 20);
		    ColumnConfig last = new ColumnConfig("date", "Last Updated", 20);
		    last.setDateTimeFormat(DateTimeFormat.getFormat("MM/dd/y"));

		    List<ColumnConfig> config = new ArrayList<ColumnConfig>();
		    config.add(company);
		    config.add(price);
		    config.add(change);
		    config.add(industry);
		    config.add(last);

		    final ColumnModel cm = new ColumnModel(config);

		    GroupingView view = new GroupingView();
		    view.setForceFit(true);
		    view.setGroupRenderer(new GridGroupRenderer() {
		      public String render(GroupColumnData data) {
		        String f = cm.getColumnById(data.field).getHeader();
		        String l = data.models.size() == 1 ? "Item" : "Items";
		        return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";
		      }
		    });

		    Grid<Stock> grid = new Grid<Stock>(store, cm);
		    grid.setView(view);
		    grid.setBorders(true);

		    w.add(grid);
		    return w;
		  }
	 
	
	 /**
		 * 模拟从后台传过来的关于MenuItem的元模型信息
		 */
		private GxtComponentMetaNodeModel getGxtComponentMetaNodeModel2() {
			Map<String, Object> map4=new HashMap<String, Object>();
			map4.put("component_model_type", ComponentTypeEnum.DESKTOP_STARTMENU_MODEL);
			map4.put("text", "222LoginView----AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER");			
			Map<String,Object> codes4 = new HashMap<String, Object>();
			 Map<String,Object> subMap = new HashMap<String, Object>();
				 EventStructureMetaModel eventStructureMetaModel = new EventStructureMetaModel();
				 eventStructureMetaModel.setControllerId("desktopStartMenuController02");
				 eventStructureMetaModel.setResponseModeId("00_02_88");
			subMap.put("eventstructuremetamodel", eventStructureMetaModel);
			codes4.put("0005", subMap);
		
		//codes1.add("0002");
		map4.put("registereventtypes", codes4);
			GxtComponentMetaNodeModel node4=new GxtComponentMetaNodeModel(map4);
			return node4;
		}
	
		/**
		 * 模拟从后台传过来的关于MenuItem的元模型信息
		 */
		private GxtComponentMetaNodeModel getGxtComponentMetaNodeModel() {
			Map<String, Object> map4=new HashMap<String, Object>();
			map4.put("component_model_type", ComponentTypeEnum.DESKTOP_STARTMENU_MODEL);
			map4.put("text", "001LoginView----AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER");			
				Map<String,Object> codes4 = new HashMap<String, Object>();
					 Map<String,Object> subMap = new HashMap<String, Object>();
						 EventStructureMetaModel eventStructureMetaModel = new EventStructureMetaModel();
						 eventStructureMetaModel.setControllerId("desktopStartMenuController01");
						 eventStructureMetaModel.setResponseModeId("00_02_66");
					subMap.put("eventstructuremetamodel", eventStructureMetaModel);
					codes4.put("0005", subMap);
				
				//codes1.add("0002");
				map4.put("registereventtypes", codes4);
			GxtComponentMetaNodeModel node4=new GxtComponentMetaNodeModel(map4);
			return node4;
		}

}
